#!/bin/bash
HOSTNAME="localhost"
EMAIL_CONTENT=""
RANDOMLONG=""
RANDOMSHORT=""
REMOTEIP=""

CONTENT_DIR=$1
MAXID=$2
ACOTFILE=$3

declare -a FROM_ARRAY
FROM_ARRAY[0]="From:\"=?utf-8?B?""`echo 美容小窍门|base64`""?=\"<Edward@localhost.com>"
FROM_ARRAY[1]="From:\"=?utf-8?B?""`echo 美容小护士|base64`""?=\"<meirong@xiaohushi.com>"
FROM_ARRAY[2]="From:\"=?utf-8?B?""`echo 美容小贴士|base64`""?=\"<meili@tieshi.com>"
FROM_ARRAY[3]="From:\"=?utf-8?B?""`echo 女人爱美丽|base64`""?=\"<woman@aimeili.com>"
FROM_ARRAY[4]="From:\"=?utf-8?B?""`echo 美丽女人|base64`""?=\"<woman@meili.com>"
FROM_ARRAY[5]="From:\"=?utf-8?B?""`echo 美容小顾问base64`""?=\"<guwen@meili.com>"
FROM_ARRAY[6]="From:\"=?utf-8?B?""`echo 美丽小管家|base64`""?=\"<meili@guanjia.com>"
FROM_ARRAY[7]="From:\"=?utf-8?B?""`echo 私人美容顾问|base64`""?=\"<meirong@guwen.com>"
FROM_ARRAY[8]="From:\"=?utf-8?B?""`echo 你的专属美容顾问|base64`""?=\"<meirong@sirenguwen.com>"
FROM_ARRAY[9]="From:\"=?utf-8?B?""`echo 你的专属美丽顾问|base64`""?=\"<meili@guwen.com>"
FROM_ARRAY[10]="From:\"=?utf-8?B?""`echo 温馨美丽窍门|base64`""?=\"<meili@qiaomen.com>"
FROM_ARRAY[11]="From:\"=?utf-8?B?""`echo 美丽的秘密你知道|base64`""?=\"<beautiful@mimi.com>"
FROM_ARRAY[12]="From:\"=?utf-8?B?""`echo 你的私人美容天使|base64`""?=\"<meirong@tianshi.com>"
FROM_ARRAY[13]="From:\"=?utf-8?B?""`echo 你的专属美丽天使|base64`""?=\"<MeiLi@tianshi.com>"
FROM_ARRAY[14]="From:\"=?utf-8?B?""`echo 美丽小天使|base64`""?=\"<MeiLi@xiaotianshi.com>"
FROM_ARRAY[15]="From:\"=?utf-8?B?""`echo 美丽天使|base64`""?=\"<MeiLi@tianshi.com>"
FROM_ARRAY_NUM=${#FROM_ARRAY[@]}
echo "number of from array:"$FROM_ARRAY_NUM

Usage(){
	echo "sendmail.sh  <content dir> <maxid> <account>"
}

PrepareMail(){
#	AppendEContent "From:\"=?utf-8?B?""`echo 美容小窍门|base64`""?=\"<Edward@localhost.com>"
	RID=$RANDOM
	AID=$((RID%FROM_ARRAY_NUM))
	AppendEContent "${FROM_ARRAY[AID]}"
	AppendEContent "To:$1"
	AppendEContent "Date:""`date -R`"
#	echo -E "$EMAIL_CONTENT"
}

ResolvIpByDns(){
	REMOTEDOMAIN=`echo $1 |awk -F \@ '{print $2}'`
	TMPDOMAIN=`dig mx $REMOTEDOMAIN|grep -1 "ANSWER SECTION"|grep MX|awk {'print $6'}`
	if [ "x"$TMPDOMAIN != "x" ]
	then 
		REMOTEIP=`basename $TMPDOMAIN .`
	fi
}

SendEmail(){
		./expect_send.sh $REMOTEIP Edward@localhost.com $1 "$EMAIL_CONTENT" $CONTENT_DIR/$2.eml
		if [ $? -eq 0 ]
		then 
			echo "$1" >> /tmp/already_send.log
		else
			echo "$1" >> /tmp/failed_send.log
		fi
}

AppendEContent(){
#	EMAIL_CONTENT=$EMAIL_CONTENT$1$'\r'$'\n'
	EMAIL_CONTENT=$EMAIL_CONTENT$1$'\n'
}

ClearEContent(){
	EMAIL_CONTENT=""
}

if [ $# -lt 3 ]
then
	Usage
	exit 1
fi

CONTENT=""
SUBJECT=""
ACCOUNT=""
i=0
while read ACCOUNT
do
	ResolvIpByDns "$ACCOUNT"
	if [ "x"$REMOTEIP != "x" ]
	then
		PrepareMail "$ACCOUNT"
		SendEmail "$ACCOUNT" $i
		ClearEContent

		i=$((i+1))
		if [ $i -ge $MAXID ]
		then
			i=0
		fi
	fi
done < $ACOTFILE
